package cn.iotab.iotkit.transport.api.access.model.message;

import cn.iotab.iotkit.transport.api.access.model.exception.IncompleteMessageException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;

/**
 * 与设备交互的原始消息响应
 * // 当请求的ack=1时，需回复Response
 */
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class OriginMessageReply {

    //必传，与requestID相等，代表只针对这个request的响应
    @NotNull
    private String id;

    @Nullable
    private Long ts;

    //必传，200代表成功，其他值都是失败。其他错误码含义待定。
    @NotNull
    private Integer code;

    //错误是展示错误信息
    @Nullable
    private String err;

    //非必传，是情况而定
    @Nullable
    private JSONObject data;

    public void from(OriginMessageReply reply) {
        this.id = reply.id;
        this.ts = reply.ts;
        this.code = reply.code;
        this.err = reply.err;
        // data是浅拷贝
        this.data = reply.data;
    }

    public void validate() {
        if (StringUtils.isBlank(this.id)) {
            throw new IncompleteMessageException("msgReply id is blank");
        }
        if (this.code == null) {
            throw new IncompleteMessageException("msgReply code is null");
        }
    }

    public static OriginMessageReply fromJson(JSONObject json) {
        OriginMessageReply reply = new OriginMessageReply();
        reply.id = json.getString("id");
        reply.ts = json.getLong("ts");
        reply.code = json.getInteger("code");
        reply.data = json.getJSONObject("data");
        reply.err = json.getString("err");
        return reply;
    }

    public JSONObject toJson() {
        JSONObject json = new JSONObject();
        json.put("id", id);
        if (this.ts != null) {
            json.put("ts", ts);
        }
        json.put("code", code);
        if (data != null) {
            json.put("data", data);
        }
        if (StringUtils.isNotBlank(err)) {
            json.put("err", err);
        }
        return json;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
